package com.ikingtech.platform.service.push.websocket;

import com.ikingtech.framework.sdk.cluster.client.ClusterClient;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.push.common.DeliverResult;
import com.ikingtech.platform.service.push.common.DeliverTypeEnum;
import com.ikingtech.platform.service.push.common.PushRequest;
import com.ikingtech.platform.service.push.websocket.cluster.ClusterNodeWebsocketPushNotifyMessage;
import com.ikingtech.platform.service.push.websocket.session.WebsocketSessionManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
public class WebsocketClusterDeliver implements WebsocketDeliver {

    private final ClusterClient clusterClient;

    @Override
    public DeliverResult send(PushRequest pushRequest, String receiverId) {
        List<WebSocketSession> sessions = WebsocketSessionManager.get(receiverId);
        if (Tools.Coll.isNotBlank(sessions)) {
            return this.execute(sessions, pushRequest);
        } else {
            ClusterNodeWebsocketPushNotifyMessage message = new ClusterNodeWebsocketPushNotifyMessage();
            message.setMessageBody(pushRequest.getBody());
            message.setReceiverId(receiverId);
            this.clusterClient.broadcast(message);
            return DeliverResult.success();
        }
    }

    @Override
    public DeliverTypeEnum type() {
        return DeliverTypeEnum.WEBSOCKET;
    }
}
